//#import "AddressManagerViewController.h"
#import <Masonry/Masonry.h>
#import "XMAddressViewCell.h"
#import "XMAddressViewController.h"
#import "XMAddressEditViewController.h"
@interface XMAddressViewController () <XMAddressViewCellDelegate,UITableViewDelegate,UITableViewDataSource,XMAddressEditViewControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *addressList;
@property (nonatomic, strong) UIButton *addAddressButton;

@end

@implementation XMAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.0];
    self.title = @"管理收货地址";
    
    // 初始化导航栏
    [self setupNavigationBar];
    
    // 初始化数据
    [self setupData];
    
    // 初始化UI
    [self setupUI];
    [self orderList];
}

- (void)setupNavigationBar {
    // 返回按钮
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back_icon"] style:UIBarButtonItemStylePlain target:self action:@selector(backButtonTapped)];
    self.navigationItem.leftBarButtonItem = backButton;
}

-(void)orderList
{
  
    NSMutableDictionary * mutableDict = @{@"orderId":@"",@"pageNo":@"1",@"pageSize":@"10"}.mutableCopy;
    [[XMNetwork shareInstance]getDataWithPath:[NSString stringWithFormat:@"%@%@",HttpInterface,orderAddress] parameters:nil needToken:NO headers:nil success:^(id  _Nonnull responseObject) {
          NSDictionary * resultDic = responseObject;
          NSArray * data = [resultDic objectForKey:@"data"];
          NSLog(@"%@",data);
         } failure:^(NSError * _Nonnull error) {
             if(error.code == 401){
                 [MBProgressHUD showError:error.localizedDescription];
                 
            }
       }];
}
- (void)setupData {
    // 模拟地址数据
    _addressList = [NSMutableArray array];
    
    // 默认地址
    NSDictionary *defaultAddress = @{
        @"id": @1,
        @"name": @"张三",
        @"phone": @"13800138000",
        @"address": @"浙江省杭州市西湖区文一西路969号",
        @"isDefault": @YES
    };
    
    // 非默认地址
    NSDictionary *address2 = @{
        @"id": @2,
        @"name": @"张三",
        @"phone": @"13800138000",
        @"address": @"上海市浦东新区张江高科技园区博云路2号浦软大厦",
        @"isDefault": @NO
    };
    
    [_addressList addObject:defaultAddress];
    [_addressList addObject:address2];
}

- (void)setupUI {
    // 创建表格视图
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.0];
    [_tableView registerClass:[XMAddressViewCell class] forCellReuseIdentifier:@"AddressCell"];
    [self.view addSubview:_tableView];
    
    // 创建添加地址按钮
    _addAddressButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    _addAddressButton.backgroundColor = [UIColor colorWithRed:0.92 green:0.23 blue:0.19 alpha:1.0];
    [_addAddressButton setTitle:@"新增见面地址" forState:UIControlStateNormal];
    [_addAddressButton setTitleColor:kColorHEX(0x333333) forState:UIControlStateNormal];
    [_addAddressButton addTarget:self action:@selector(addAddressButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_addAddressButton];

    CAGradientLayer *gradientLayer = [GradientHelper createGradientWithFrame:CGRectMake(0, 0, kScreenWidth, 44)
                                                                           startColor:kColorHEX(0xFFD800)
                                                                             endColor:kColorHEX(0xFFE44E)];
        
        // 将渐变图层添加到按钮的layer
    [_addAddressButton.layer insertSublayer:gradientLayer atIndex:0];
    _addAddressButton.layer.masksToBounds = YES;
    _addAddressButton.layer.cornerRadius = 22;
    // 设置约束
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(_addAddressButton.mas_top).offset(-15);
    }];
    
    [_addAddressButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(28);
        make.right.equalTo(self.view).offset(-28);
        make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-15);
        make.height.mas_equalTo(44);
    }];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _addressList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XMAddressViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddressCell" forIndexPath:indexPath];
    
    NSDictionary *address = _addressList[indexPath.row];
    [cell configureWithAddress:address];
    cell.delegate = self;
    cell.indexPath = indexPath;
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 130;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - AddressCellDelegate

- (void)addressCell:(XMAddressViewCell *)cell didSelectDefault:(NSIndexPath *)indexPath {
    // 更新默认地址
    for (int i = 0; i < _addressList.count; i++) {
        NSMutableDictionary *address = [_addressList[i] mutableCopy];
        if (i == indexPath.row) {
            address[@"isDefault"] = @YES;
        } else {
            address[@"isDefault"] = @NO;
        }
        _addressList[i] = address;
    }
    
    [_tableView reloadData];
}

- (void)addressCell:(XMAddressViewCell *)cell didClickEdit:(NSIndexPath *)indexPath {
    // 跳转到编辑地址页面
    
    XMAddressEditViewController *addressVC = [[XMAddressEditViewController alloc] init];
    addressVC.delegate = self;
    addressVC.isEditMode = NO;
    [addressVC showInViewController:self animated:YES];
}

- (void)addressCell:(XMAddressViewCell *)cell didClickDelete:(NSIndexPath *)indexPath {
    // 删除地址确认
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确认删除" message:@"确定要删除这个收货地址吗？" preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [self.addressList removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
        // 如果删除的是默认地址，将第一个地址设为默认
        if ([self.addressList count] > 0 && [[self.addressList[0] objectForKey:@"isDefault"] boolValue] == NO) {
            NSMutableDictionary *firstAddress = [self.addressList[0] mutableCopy];
            firstAddress[@"isDefault"] = @YES;
            self.addressList[0] = firstAddress;
            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        }
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - AddAddressDelegate

- (void)didAddNewAddress:(NSDictionary *)address {
    [_addressList addObject:address];
    [_tableView reloadData];
}

- (void)didEditAddress:(NSDictionary *)address atIndex:(NSInteger)index {
    _addressList[index] = address;
    [_tableView reloadData];
}

#pragma mark - Button Actions

- (void)backButtonTapped {
    [self.navigationController popViewControllerAnimated:YES];
}
 
#pragma mark - AddressEditTableViewControllerDelegate

- (void)addressEditController:(id)controller didSaveAddress:(NSDictionary *)address {
    NSLog(@"保存的地址: %@", address);
    
    // 这里可以更新地址列表
}

- (void)addAddressButtonTapped {
    // 跳转到新增地址页面
//    AddAddressViewController *addVC = [[AddAddressViewController alloc] init];
//    addVC.delegate = self;
//    addVC.isEditMode = NO;
//    [self.navigationController pushViewController:addVC animated:YES];
}

@end    
